/*
 * Project: babylon File Created at 2011-7-26 Copyright 2011 Alibaba.com Corporation Limited. All rights reserved. This
 * software is the confidential and proprietary information of Alibaba Company. ("Confidential Information"). You shall
 * not disclose such Confidential Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with Alibaba.com.
 */

package com.whale.util;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.MediaColumns;

/**
 * @author qibao.xieqb
 */
public class FileUtil {

    private static final String BASE_PATH = "whale";

    /**
     * 获得sdcard上的路径
     */
    public static File getBasePath() throws IOException {
        File basePath = new File(Environment.getExternalStorageDirectory(), BASE_PATH);
        if (!basePath.exists()) {
            if (!basePath.mkdirs()) {
                throw new IOException("file cannot be created!" + basePath.toString());
            }
        }
        if (!basePath.isDirectory()) {
            throw new IOException("file is not a directory!" + basePath.toString());
        }
        return basePath;
    }

    public static File getBasePath(Context context) throws IOException {
        File basePath = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
        if (!basePath.exists()) {
            if (!basePath.mkdirs()) {
                throw new IOException("file cannot be created!" + basePath.toString());
            }
        }
        if (!basePath.isDirectory()) {
            throw new IOException("file is not a directory!" + basePath.toString());
        }
        return basePath;
    }

    /**
     * 根据uri获得文件的确切路径
     * 
     * @return
     */
    public static String getRealPathFromURI(Uri contentUri, Activity a) {
        String[] proj = { MediaColumns.DATA };
        Cursor cursor = a.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public static File getCameraFile(Context context) {
        try {
            return new File(getBasePath(context), "upload.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
